package top.csmcool.musicapi.util;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import top.csmcool.musicapi.domain.UserPlatformBindInfo;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 音乐请求工具
 * 实现并发下数据覆盖问题
 * @Description
 * @Author shizhe
 * @Date 2025/2/8
 */

@Component
@RequiredArgsConstructor
public class MusicRequestUtil {

    private final RestTemplate restTemplate;

    public JSONObject sendRequestAutowiredJson(JSONObject jsonObject, String url) {
        JSONObject result = null;
        UserPlatformBindInfo userPlatformBindInfo = TreadLocalUtil.userPlatformBindInfo.get();
        if(userPlatformBindInfo == null) {
            return null;
        }
        // 获取请求地址
        final long time = Timestamp.valueOf(LocalDateTime.now()).getTime();
        if(!url.endsWith("&")) {
            url += "?";
        }
        String fullPathURL = userPlatformBindInfo.getPlatformUrl() + url + "timestamp="+time;;
        final HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        if(StringUtils.hasText(userPlatformBindInfo.getCookie())) {
            httpHeaders.add(HttpHeaders.COOKIE, userPlatformBindInfo.getCookie());
        }
        final HttpEntity<String> stringHttpEntity = new HttpEntity<String>(jsonObject.toString(), httpHeaders);
        try {
            final ResponseEntity<String> responseEntity = restTemplate.exchange(fullPathURL, HttpMethod.POST, stringHttpEntity, String.class);
            String body = responseEntity.getBody();
            result = JSONUtil.parseObj(body);

            final HttpHeaders headers = responseEntity.getHeaders();
            final List<String> setCookie = headers.get("set-cookie");
            if (setCookie != null) {
                String cookieString = parseSetCookie(setCookie.toString());
                userPlatformBindInfo.setCookie(cookieString);
                TreadLocalUtil.setUserPlatformBindInfoThreadLocal(userPlatformBindInfo);
            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String parseSetCookie(String setCookie) {
        if (setCookie == null) {
            return "";
        }
        System.out.println("解析前cookie是" + setCookie);
        final String[] split = setCookie.split(";, ");
        final Optional<String> cookieStringOptional = Arrays.stream(split).map(x -> {
            return x.split(";")[0] + "; ";
        }).reduce((x, y) -> x + y);
        String cookieString = cookieStringOptional.get() + "]";
        System.out.println("解析后cookie是:" + cookieString);
        return cookieString;
    }
}
